from flask import Blueprint,request,make_response
from utils import sendsms,restful,dxcache
from utils.captcha import Captcha
# from exts import alidayu
from .forms import SMSCaptchaForm
from io import BytesIO
bp = Blueprint('common',__name__,url_prefix='/c')
from datetime import datetime
# from tasks import send_sms_captcha

@bp.route('/captcha/')
def graph_captcha():
    text,image = Captcha.gene_graph_captcha()
    dxcache.set(text.lower(),text.lower())
    out = BytesIO()
    image.save(out,'png')
    out.seek(0)
    resp = make_response(out.read())
    resp.content_type = 'image/png'
    return resp

# @bp.route('/sms_captcha/',methods=['POST'])
# def sms_captcha():
    # #?telephone=xxxxx
    # telephone = request.args.get('telephone')
    # if not telephone:
    #     return restful.params_error('请输入正确的手机号')
    # captcha = '尊敬的用户你好，您的验证码是'+Captcha.gene_text(number=4)
    # print(captcha,telephone)
    # result =Send_sms.send_sms(telephone,text=captcha)
    # print(result)
    # if result:
    #     return restful.success()
    # else:
    #     return restful.params_error('请输入正确的手机号！')
@bp.route('/sms_captcha/',methods=['POST'])
def sms_captcha():
    form = SMSCaptchaForm(request.form)
    if form.validate():
        telephone = form.telephone.data
        captcha =Captcha.gene_text(number=4)
        # print(captcha,telephone)
        result =sendsms.send_sms(telephone, text=captcha)
        #使用celery 实现异步发送
        # result = send_sms_captcha.delay(telephone,captcha)
        if result:
            dxcache.set(telephone,captcha,timeout=120)
            print('此时得到的验证码是：',dxcache.get(telephone))
            return restful.success()
        else:
            return restful.params_error('请输入正确的手机号！')
    else:
        return restful.params_error('参数错误！')

@bp.app_template_filter('handle_time')
def handle_time(time):
    if isinstance(time,datetime):
        now = datetime.now()
        timestamp = (now - time).total_seconds()
        if timestamp < 60:
            return '刚刚'
        elif timestamp >= 60 and timestamp <= 60 * 60:
            minute = timestamp / 60
            return '%s分钟前' % int(minute)
        elif timestamp >= 60*60 and timestamp <= 60*60 *24:
            hour = timestamp /(60 * 60)
            return "%s小时前" % int(hour)
        elif timestamp >= 60 * 60 * 24 and timestamp <= 60 * 60 * 24 * 30:
            day = timestamp / (60 * 60 * 24)
            return "%s天前" % int(day)
        else:
            return time.strftime('%Y%m%d %H:%M')
    else:
        return time

